package com.my12306.user.exception.auth;

import com.my12306.common.enums.CodeEnum;
import com.my12306.common.util.response.ResponseData;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义token校验一层信息，用于token校验失败后返回相关信息，
 *
 * @Author:苏牧夕
 * @Date:2020/5/28 13:04
 * @Version 1.0
 */
public class AuthExceptionEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        System.out.println("异常");
        ResponseData result = ResponseData.fail(CodeEnum.UNAUTHORIZATION.getCode(), CodeEnum.UNAUTHORIZATION.getMessage());
        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
        httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(httpServletResponse.getOutputStream(), result);
    }
}
